var app = new Vue({
	el: '#app',
	data: {
		userMsg: {
			isLogin: false,
			id: null,
			account: null,
			name: null,
			headimg: null
		},
		news: {},
		newsid: '',
		comments: [],
		textarea: '',
		moduleList: []
	},
	watch: {
	},
	methods: {
		logout: function(){
			var self = this;

			swal({ 
				title: "确定退出吗？", 
				type: "warning",
				showCancelButton: true, 
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "确定", 
  				cancelButtonText: "取消"
			},function(){
				$.post("/api/logout",{},function(data,status){
					if (data.success = "ok") {
						self.getLoginStatus();
					}
				});
			});

		},
		getLoginStatus: function(){
			var self = this;
			$.get('/api/isLogin',function(data,status){
				if (data.success == "ok") {
					self.userMsg.isLogin = true;
					self.userMsg.name = data.result.name;
					self.userMsg.id = data.result.id;
					self.userMsg.account = data.result.account;
					self.userMsg.headimg = data.result.headimg;
				} else {
					self.userMsg.isLogin = false;
				}
			})
		},
		getQueryString: function(name) { 
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
			var r = window.location.search.substr(1).match(reg); 
			if (r != null) return unescape(r[2]); return null; 
		},
		getNews: function(id){
			var self = this;
			$.post('/api/getNews',{"id":id},function(data,status){
				if (data.success == "ok") {
					self.news = data.result;
				} else {
					swal("网络错误","请刷新充实","error");
				}
			})
		},
		getComment: function(id){
			var self = this;
			$.post('/api/getComment',{"id":id},function(data,status){
				if (data.success == "ok") {
					self.comments = data.result;
				} else {
					swal("网络错误","请刷新充实","error");
				}
			})
		},
		getModule: function(){
			var self = this;
			$.post('/api/getModule',function(data,status){
				if (data.success == "ok") {
					self.moduleList = data.result;
				} else {
					swal("网络错误","请重试","error");
				}
			})

		},
		post: function(){
			var self = this;
			console.log(self.userMsg)
			if (self.userMsg.isLogin == false) {
				swal("请先登录","","error");
				return ;
			}
			var data = {
				"id": self.userMsg.id,
				"news_id": self.newsid,
				"comment": self.textarea
			}
			$.post('/api/createComment',data,function(data,status){
				if (data.success == "ok") {
					self.getComment(self.newsid);
					self.textarea = "";
				} else {
					if (data.msg == "该用户已被禁用") {
						swal("该用户已被禁用","error");
					} else {
						swal("网络错误","请刷新重试","error");
					}
				}
			})
		}

	},
	mounted: function(){
		this.getLoginStatus();
		var id = this.getQueryString("id");
		this.newsid = id;
		this.getNews(id);
		this.getComment(id);
		this.getModule();
	}
})
